import Tetris from "@/composable/tetrisBlocks"
export function deepCopy(array: any[]): any[] {
    return JSON.parse(JSON.stringify(array))
}

export function rotate(array: number[][]): number[][] {
    return [
        [array[0][3], array[1][3], array[2][3], array[3][3]],
        [array[0][2], array[1][2], array[2][2], array[3][2]],
        [array[0][1], array[1][1], array[2][1], array[3][1]],
        [array[0][0], array[1][0], array[2][0], array[3][0]],
    ]
}
// 合并当前块
export function merge(des: number[][], src: Tetris) {
    for (let r = 0; r < src.blocks.length; r++) {
        for (let c = 0; c < src.blocks[r].length; c++) {
            const dr = r + src.position.row, dc = c + src.position.col
            if (src.blocks[r][c]
                && (dr >= 0 && dr < des.length)
                && (dc >= 0 && dc < des[dr].length)
                && !des[dr][dc]
            ) {
                des[dr][dc] = src.blocks[r][c]
            }
        }
    }
    return des
}
// 碰撞检测
// 到底检测时 offsetCol = 0, offsetRow = 1, ro = false
export function isCollided(tetris: Tetris, con: number[][], offsetCol: number, offsetRow: number, ro: boolean): boolean {
    let tmpBlocks: number[][] = deepCopy(tetris.blocks)
    let { row: tr, col: tc } = tetris.position

    tr += offsetRow
    tc += offsetCol
    if (ro) {
        tr = tetris.position.row
        tc = tetris.position.col
        tmpBlocks = rotate(tmpBlocks)
    }

    for (let r = 0; r < tmpBlocks.length; r++) {
        const pr = tr + r
        for (let c = 0; c < tmpBlocks[r].length; c++) {
            const pc = tc + c
            if (tmpBlocks[r][c] && pr < 0 && (pc < 0 || pc >= 10)) return true
            if (pr < 0) continue
            if (tmpBlocks[r][c] && (pc < 0 || pc >= 10 || pr >= 20 || con[pr][pc])) return true
        }
    }
    return false
}
// 消除
export function clearRow(orign: number[][]): number[] {
    let num: number[] = []
    for (let i = 0; i < orign.length; i++) {
        if (orign[i].every(v => v > 0)) {
            // num++
            for (let key = 0; key < 10; key++) {
                num.push(i * 10 + key)
            }
            //     orign.splice(i, 1)
            //     orign.unshift(new Array(10).fill(0))
        }
    }
    return num
}